<template>
  <div class="main">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="font-medium">比赛列表</span>
            <div class="data-filter-buttons">
              <el-button
                :type="dateFilter === 'current' ? 'primary' : 'default'"
                size="small"
                @click="handleDateFilterChange('current')"
              >
                当前数据
              </el-button>
              <el-button
                :type="dateFilter === 'historical' ? 'primary' : 'default'"
                size="small"
                @click="handleDateFilterChange('historical')"
              >
                往期数据
              </el-button>
            </div>
          </div>
          <div class="header-actions">
            <el-button
              type="info"
              size="small"
              @click="handlePreviousDayQuery"
              :loading="loading"
            >
              前一天数据
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleResetTimeFilter"
              v-if="timeRange.startTime || timeRange.endTime"
            >
              重置时间
            </el-button>
            <el-upload
              ref="uploadRef"
              :show-file-list="false"
              :before-upload="handleImport"
              accept=".xlsx,.xls,.csv"
              :auto-upload="true"
            >
              <el-button type="primary" :icon="Upload"> 一键导入 </el-button>
            </el-upload>
            <el-upload
              ref="scoreUploadRef"
              :show-file-list="false"
              :before-upload="handleScoreImport"
              accept=".xlsx,.xls,.csv"
              :auto-upload="true"
            >
              <el-button type="success" :icon="Upload"> 比分更新 </el-button>
            </el-upload>
          </div>
        </div>
      </template>

      <div class="w-full">
        <pure-table
          ref="tableRef"
          :data="flattenedDataList"
          :columns="columns"
          :pagination="pagination"
          :paginationSmall="true"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          :span-method="handleSpanMethod"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
          :loading="loading"
        >
          <template #operation="{ row }">
            <el-button
              v-if="row.isFirstBetting"
              class="reset-margin"
              link
              type="primary"
              size="small"
              @click="handleView(row)"
            >
              详情
            </el-button>
            <el-button
              v-if="row.isFirstBetting"
              class="reset-margin"
              link
              type="warning"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.isFirstBetting"
              class="reset-margin"
              link
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </pure-table>
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <MatchDetail v-model:visible="detailVisible" :match-data="currentMatch" />

    <!-- 编辑比赛弹窗 -->
    <MatchEdit
      v-model:visible="editVisible"
      :match-data="currentMatch"
      @submit="handleEditSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, h } from "vue";
import {
  getMatchList,
  importMatches,
  importScores,
  deleteMatch,
  updateMatch,
  type MatchData,
  type BettingData
} from "@/api/matches";
import { ElInput, ElButton } from "element-plus";
import { PureTable } from "@pureadmin/table";
import { formatDateTime } from "../../utils/formatTime";
import MatchDetail from "./components/MatchDetail.vue";
import MatchEdit from "./components/MatchEdit.vue";
import BettingButtons from "./components/BettingButtons.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { Upload } from "@element-plus/icons-vue";

// 扁平化后的数据类型
type FlattenedMatchData = MatchData &
  BettingData & {
    isFirstBetting: boolean; // 标识是否为该比赛的第一个投注信息
    bettingCount: number; // 该比赛的投注信息总数
    bettingIndex: number; // 当前投注信息在该比赛中的索引
    homeWinRate?: number | null; // 主队胜率
    awayWinRate?: number | null; // 客队胜率
    boldRecommendation?: string | null; // 胆推荐
    homeScore?: number | null; // 主队比分
    awayScore?: number | null; // 客队比分
    matchResult?: string | null; // 赛果
    predictionHit?: boolean | null; // 预测命中
  };

// 编辑状态管理
const editingWinRates = ref<
  Record<number, { homeWinRate: number | null; awayWinRate: number | null }>
>({});

defineOptions({
  name: "MatchesList"
});

const tableRef = ref();
const scoreUploadRef = ref(); // 比分上传组件引用
const loading = ref(true);
const dataList = ref<MatchData[]>([]);
const detailVisible = ref(false);
const editVisible = ref(false);
const currentMatch = ref<MatchData | null>(null);
// 数据筛选类型：默认显示当前数据
const dateFilter = ref<"current" | "historical">("current");

// 时间范围查询状态
const timeRange = ref<{
  startTime: string | null;
  endTime: string | null;
}>({
  startTime: null,
  endTime: null
});

// 前一天查询计数器，用于追踪连续点击次数
const previousDayClickCount = ref(0);

const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true
});

// 数据扁平化处理
const flattenedDataList = computed(() => {
  const result: FlattenedMatchData[] = [];

  dataList.value.forEach(match => {
    const bettings = match.bettings || [];

    // 如果没有投注信息，也要显示一行比赛信息
    if (bettings.length === 0) {
      result.push({
        ...match,
        id: 0,
        matchId: match.id,
        jingcaiNumber: null,
        beidanNumber: "",
        jingcaiSingle: null,
        jingcaiHandicap: null,
        beidanHandicap: "",
        winOdds: "",
        drawOdds: null,
        loseOdds: "",
        homeScore: null,
        awayScore: null,
        matchResult: null,
        predictionHit: null,
        createdAt: "",
        updatedAt: "",
        isFirstBetting: true,
        bettingCount: 0,
        bettingIndex: 0
      });
    } else {
      // 为每个投注信息创建一行数据
      bettings.forEach((betting, index) => {
        result.push({
          ...match,
          ...betting,
          isFirstBetting: index === 0,
          bettingCount: bettings.length,
          bettingIndex: index
        });
      });
    }
  });

  return result;
});

// 单元格合并方法
const handleSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  // 需要合并的比赛信息列（包括胜率列和胆推荐列）
  const matchColumns = [
    "matchTime",
    "leagueName",
    "homeTeam",
    "awayTeam",
    "homeWinRate",
    "awayWinRate",
    "boldRecommendation"
  ];

  // 处理比赛信息列的合并
  if (matchColumns.includes(column.property)) {
    if (row.isFirstBetting) {
      return {
        rowspan: row.bettingCount || 1,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }

  // 处理操作列的合并
  if (column.property === "operation") {
    if (row.isFirstBetting) {
      return {
        rowspan: row.bettingCount || 1,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }

  return {
    rowspan: 1,
    colspan: 1
  };
};

const columns: TableColumnList = [
  {
    label: "比赛时间",
    prop: "matchTime",
    minWidth: 160,
    formatter: ({ matchTime }) => {
      if (!matchTime) return "-";
      const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      const date = new Date(matchTime);
      const weekday = weekdays[date.getDay()];
      return `${formatDateTime(matchTime)} ${weekday}`;
    }
  },
  {
    label: "联赛",
    prop: "leagueName",
    minWidth: 80
  },
  {
    label: "主队",
    prop: "homeTeam",
    minWidth: 80
  },
  {
    label: "客队",
    prop: "awayTeam",
    minWidth: 80
  },
  {
    label: "主队胜率(%)",
    prop: "homeWinRate",
    minWidth: 120,
    cellRenderer: ({ row }) => {
      const matchId = row.matchId || row.id;
      const currentValue =
        editingWinRates.value[matchId]?.homeWinRate ?? row.homeWinRate ?? null;

      return h(ElInput, {
        modelValue: currentValue,
        placeholder: "请输入主队胜率",
        type: "number",
        min: 0,
        max: 100,
        step: 0.1,
        size: "small",
        class: "win-rate-input",
        "onUpdate:modelValue": (value: string) => {
          if (!editingWinRates.value[matchId]) {
            editingWinRates.value[matchId] = {
              homeWinRate: null,
              awayWinRate: null
            };
          }
          editingWinRates.value[matchId].homeWinRate = value
            ? parseFloat(value)
            : null;
        },
        onBlur: () => {
          const value =
            editingWinRates.value[matchId]?.homeWinRate ?? row.homeWinRate;
          if (value !== row.homeWinRate) {
            handleUpdateWinRate(matchId, "homeWinRate", value);
          }
        }
      });
    }
  },
  {
    label: "客队胜率(%)",
    prop: "awayWinRate",
    minWidth: 120,
    cellRenderer: ({ row }) => {
      const matchId = row.matchId || row.id;
      const currentValue =
        editingWinRates.value[matchId]?.awayWinRate ?? row.awayWinRate ?? null;

      return h(ElInput, {
        modelValue: currentValue,
        placeholder: "请输入客队胜率",
        type: "number",
        min: 0,
        max: 100,
        step: 0.1,
        size: "small",
        class: "win-rate-input",
        "onUpdate:modelValue": (value: string) => {
          if (!editingWinRates.value[matchId]) {
            editingWinRates.value[matchId] = {
              homeWinRate: null,
              awayWinRate: null
            };
          }
          editingWinRates.value[matchId].awayWinRate = value
            ? parseFloat(value)
            : null;
        },
        onBlur: () => {
          const value =
            editingWinRates.value[matchId]?.awayWinRate ?? row.awayWinRate;
          if (value !== row.awayWinRate) {
            handleUpdateWinRate(matchId, "awayWinRate", value);
          }
        }
      });
    }
  },
  {
    label: "胆",
    prop: "boldRecommendation",
    minWidth: 160,
    cellRenderer: ({ row }) => {
      const matchId = row.matchId || row.id;
      const currentValue = row.boldRecommendation || "none";

      return h("div", { class: "bold-recommendation-buttons" }, [
        h(
          ElButton,
          {
            type: currentValue === "recommend_bold" ? "primary" : "default",
            size: "small",
            onClick: () =>
              handleBoldRecommendationChange(
                matchId,
                currentValue === "recommend_bold" ? "none" : "recommend_bold"
              )
          },
          { default: () => "推荐胆" }
        ),
        h(
          ElButton,
          {
            type: currentValue === "recommend_stable" ? "warning" : "default",
            size: "small",
            onClick: () =>
              handleBoldRecommendationChange(
                matchId,
                currentValue === "recommend_stable"
                  ? "none"
                  : "recommend_stable"
              )
          },
          { default: () => "推荐稳胆" }
        )
      ]);
    }
  },
  {
    label: "竞彩编号",
    prop: "jingcaiNumber",
    minWidth: 80,
    formatter: ({ jingcaiNumber }) => jingcaiNumber || "-"
  },
  {
    label: "北单编号",
    prop: "beidanNumber",
    minWidth: 80,
    formatter: ({ beidanNumber }) => beidanNumber || "-"
  },
  {
    label: "竞彩单关",
    prop: "jingcaiSingle",
    minWidth: 80,
    formatter: ({ jingcaiSingle }) => jingcaiSingle || "-"
  },
  {
    label: "竞彩让球",
    prop: "jingcaiHandicap",
    minWidth: 80,
    formatter: ({ jingcaiHandicap }) => jingcaiHandicap || "-"
  },
  {
    label: "北单让球",
    prop: "beidanHandicap",
    minWidth: 80,
    formatter: ({ beidanHandicap }) => beidanHandicap || "-"
  },
  {
    label: "主队比分",
    prop: "homeScore",
    minWidth: 80,
    formatter: ({ homeScore }) => homeScore !== null && homeScore !== undefined ? homeScore : "-"
  },
  {
    label: "客队比分",
    prop: "awayScore",
    minWidth: 80,
    formatter: ({ awayScore }) => awayScore !== null && awayScore !== undefined ? awayScore : "-"
  },
  {
    label: "赛果",
    prop: "matchResult",
    minWidth: 80,
    formatter: ({ matchResult }) => matchResult || "-"
  },
  {
    label: "预测命中",
    prop: "predictionHit",
    minWidth: 80,
    cellRenderer: ({ row }) => {
      if (row.predictionHit === null || row.predictionHit === undefined) {
        return "-";
      }
      return h("span", {
        class: row.predictionHit ? "text-green-500" : "text-red-500"
      }, row.predictionHit ? "命中" : "未命中");
    }
  },
  {
    label: "胜平负",
    prop: "betting",
    minWidth: 300,
    cellRenderer: ({ row }) => {
      // 只有当有投注ID时才显示按钮
      if (row.id && row.id > 0) {
        return h(BettingButtons, {
          bettingId: row.id,
          winOdds: row.winOdds,
          drawOdds: row.drawOdds,
          loseOdds: row.loseOdds,
          recommendedResult: row.recommendedResult
        });
      }
      return "-";
    }
  },
  {
    label: "操作",
    fixed: "right",
    width: 140,
    slot: "operation"
  }
];

const getTableData = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    // 如果有时间范围，添加到参数中，但不添加dateFilter
    if (timeRange.value.startTime && timeRange.value.endTime) {
      params.startTime = timeRange.value.startTime;
      params.endTime = timeRange.value.endTime;
    } else {
      // 只有在没有时间范围筛选时才传递dateFilter参数
      params.dateFilter = dateFilter.value;
    }

    const { data } = await getMatchList(params);

    if (data) {
      dataList.value = data.data;
      pagination.total = data.total;
    } else {
      message("出错了，请重试", { type: "error" });
    }
  } catch (error) {
    message("获取数据失败", { type: "error" });
  } finally {
    loading.value = false;
  }
};

/** 处理数据筛选切换 */
const handleDateFilterChange = (filter: "current" | "historical") => {
  dateFilter.value = filter;
  pagination.currentPage = 1; // 重置到第一页
  getTableData(); // 重新获取数据
};

/** 处理前一天数据查询 */
const handlePreviousDayQuery = () => {
  const now = new Date();
  
  // 每次点击都往前推24小时
  const daysBack = previousDayClickCount.value + 1;
  previousDayClickCount.value = daysBack;
  
  // 计算目标日期（往前推 daysBack 天）
  const endDate = new Date(now);
  endDate.setDate(endDate.getDate() - (daysBack - 1)); // 结束日期
  
  // 设置结束时间：结束日期的12:30
  const endTime = new Date(endDate);
  endTime.setHours(12, 30, 0, 0);
  
  // 设置开始时间：结束日期前一天的12:30
  const startTime = new Date(endTime);
  startTime.setDate(startTime.getDate() - 1);
  
  // 格式化时间为 ISO 字符串
  timeRange.value = {
    startTime: startTime.toISOString(),
    endTime: endTime.toISOString()
  };
  
  // 重置分页并获取数据
  pagination.currentPage = 1;
  getTableData();
  
  // 显示提示信息
  const formatDate = (date: Date) => {
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${month}月${day}日 ${hours}:${minutes}`;
  };
  
  message(`查询时间范围：${formatDate(startTime)} - ${formatDate(endTime)}`, { 
    type: "info" 
  });
};

/** 重置时间筛选 */
const handleResetTimeFilter = () => {
  timeRange.value = {
    startTime: null,
    endTime: null
  };
  previousDayClickCount.value = 0;
  pagination.currentPage = 1;
  getTableData();
  message("已重置时间筛选", { type: "success" });
};

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

const handleView = (row: FlattenedMatchData) => {
  // 从扁平化数据中构造完整的比赛数据
  const matchData: MatchData = {
    id: row.matchId || row.id,
    matchTime: row.matchTime,
    leagueName: row.leagueName,
    homeTeam: row.homeTeam,
    awayTeam: row.awayTeam,
    homeTeamLogo: row.homeTeamLogo,
    awayTeamLogo: row.awayTeamLogo,
    externalId: row.externalId,
    createdAt: row.createdAt,
    updatedAt: row.updatedAt,
    bettings:
      dataList.value.find(match => match.id === (row.matchId || row.id))
        ?.bettings || []
  };
  currentMatch.value = matchData;
  detailVisible.value = true;
};

/** 处理文件导入 */
const handleImport = async (file: File) => {
  try {
    loading.value = true;
    await importMatches(file);
    message("导入成功", { type: "success" });
    getTableData(); // 刷新列表
  } catch (error) {
    message("导入失败，请检查文件格式", { type: "error" });
  } finally {
    loading.value = false;
  }
  return false; // 阻止Element Plus的默认上传行为
};

/** 处理比分导入 */
const handleScoreImport = async (file: File) => {
  try {
    loading.value = true;
    await importScores(file);
    message("比分更新成功", { type: "success" });
    getTableData(); // 刷新列表
  } catch (error) {
    message("比分更新失败，请检查文件格式", { type: "error" });
  } finally {
    loading.value = false;
  }
  return false; // 阻止Element Plus的默认上传行为
};

/** 处理编辑比赛 */
const handleEdit = (row: FlattenedMatchData) => {
  // 从扁平化数据中构造完整的比赛数据
  const matchData: MatchData = {
    id: row.matchId || row.id,
    matchTime: row.matchTime,
    leagueName: row.leagueName,
    homeTeam: row.homeTeam,
    awayTeam: row.awayTeam,
    homeTeamLogo: row.homeTeamLogo,
    awayTeamLogo: row.awayTeamLogo,
    externalId: row.externalId,
    createdAt: row.createdAt,
    updatedAt: row.updatedAt,
    bettings:
      dataList.value.find(match => match.id === (row.matchId || row.id))
        ?.bettings || []
  };
  currentMatch.value = matchData;
  editVisible.value = true;
};

/** 处理编辑提交 */
const handleEditSubmit = async (updateData: Partial<MatchData>) => {
  if (!currentMatch.value) return;

  try {
    await updateMatch(currentMatch.value.id, updateData);
    message("更新成功", { type: "success" });
    getTableData(); // 刷新列表
  } catch (error) {
    message("更新失败", { type: "error" });
  }
};

/** 处理胆推荐变更 */
const handleBoldRecommendationChange = async (
  matchId: number,
  value: "recommend_bold" | "recommend_stable" | "none"
) => {
  try {
    await updateMatch(matchId, { boldRecommendation: value });
    message(value === "none" ? "已取消胆推荐" : "胆推荐更新成功", {
      type: "success"
    });
    getTableData(); // 刷新列表
  } catch (error) {
    message("胆推荐更新失败", { type: "error" });
  }
};

/** 处理胜率更新 */
const handleUpdateWinRate = async (
  matchId: number,
  field: "homeWinRate" | "awayWinRate",
  value: number | null
) => {
  if (value === null || value === undefined) {
    message("请输入有效的胜率值", { type: "warning" });
    return;
  }

  if (value < 0 || value > 100) {
    message("胜率值应在0-100之间", { type: "warning" });
    return;
  }

  try {
    const updateData = { [field]: value };
    await updateMatch(matchId, updateData);
    message("胜率更新成功", { type: "success" });

    // 清除编辑状态
    if (editingWinRates.value[matchId]) {
      delete editingWinRates.value[matchId][field];
      if (
        !editingWinRates.value[matchId].homeWinRate &&
        !editingWinRates.value[matchId].awayWinRate
      ) {
        delete editingWinRates.value[matchId];
      }
    }

    getTableData(); // 刷新列表
  } catch (error) {
    message("胜率更新失败", { type: "error" });
  }
};

/** 处理删除比赛 */
const handleDelete = async (row: FlattenedMatchData) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除比赛 "${row.homeTeam} vs ${row.awayTeam}" 吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 使用正确的比赛ID进行删除
    const matchId = row.matchId || row.id;
    await deleteMatch(matchId);
    message("删除成功", { type: "success" });
    getTableData(); // 刷新列表
  } catch (error) {
    if (error !== "cancel") {
      message("删除失败", { type: "error" });
    }
  }
};

onMounted(() => {
  getTableData();
});
</script>

<style scoped lang="scss">
.main {
  margin: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.data-filter-buttons {
  display: flex;
  gap: 8px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

// 表格行高和居中样式
:deep(.el-table) {
  .el-table__row {
    height: 60px; // 增加行高
    
    .el-table__cell {
      padding: 12px 0; // 增加内边距
      vertical-align: middle; // 垂直居中
      
      .cell {
        display: flex;
        align-items: center; // 内容垂直居中
        justify-content: flex-start;
        min-height: 36px; // 最小高度确保居中效果
        line-height: 1.4; // 行间距
        word-wrap: break-word; // 自动换行
        word-break: break-all; // 强制换行
      }
    }
  }
  
  // 表头样式
  .el-table__header-wrapper {
    .el-table__cell {
      padding: 12px 0;
      
      .cell {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        font-weight: 600;
      }
    }
  }
}

.bold-recommendation-buttons {
  display: flex;
  gap: 6px;
  align-items: center;

  :deep(.el-button) {
    border-radius: 4px;
    font-weight: 500;
    transition: all 0.3s ease;
    
    &.el-button--primary {
      background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
      border-color: #409eff;
      box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
      
      &:hover {
        background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(64, 158, 255, 0.4);
      }
    }
    
    &.el-button--warning {
      background: linear-gradient(135deg, #e6a23c 0%, #cf9236 100%);
      border-color: #e6a23c;
      box-shadow: 0 2px 4px rgba(230, 162, 60, 0.3);
      
      &:hover {
        background: linear-gradient(135deg, #ebb563 0%, #e6a23c 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(230, 162, 60, 0.4);
      }
    }
    
    &.el-button--default {
      background: #ffffff;
      border-color: #dcdfe6;
      color: #606266;
      
      &:hover {
        background: #f5f7fa;
        border-color: #c0c4cc;
        color: #409eff;
        transform: translateY(-1px);
      }
    }
  }
}

:deep(.win-rate-input) {
  .el-input__wrapper {
    border-radius: 6px;
    transition: all 0.2s ease;

    &:hover {
      border-color: var(--el-color-primary);
    }

    &:focus-within {
      border-color: var(--el-color-primary);
      box-shadow: 0 0 0 2px var(--el-color-primary-light-8);
    }
  }

  // 隐藏数字输入框的上下按钮
  input[type="number"]::-webkit-outer-spin-button,
  input[type="number"]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }

  input[type="number"] {
    -moz-appearance: textfield;
    appearance: textfield;
  }
}
</style>
